#include "stm32wig.h"
#include "ui_stm32wig.h"
#include "globalval.h"
#include "mqtthandler.h"
#include <QPushButton>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QLabel>
#include <QTimer>
#include <QDateTime>

Stm32Wig::Stm32Wig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Stm32Wig)
{
    ui->setupUi(this);
//    label = new QLabel(this);
//    ui->verticalLayout->addWidget(label);
//    label->setGeometry(20,420,200,50);


//   label->setStyleSheet("background-color: rgba(255, 255, 255, 0);");
    ui->label->setStyleSheet("background-color: rgba(255, 255, 255, 0);color: black;font-family: '黑体'; font-size: 18px;");
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout,this,&Stm32Wig::updateTime);
    timer->start(1000);
    updateTime();


}

Stm32Wig::~Stm32Wig()
{
    delete ui;
}

void Stm32Wig::mqttSlot(const QByteArray &payload)
{
    qDebug() << "Stm32wig";
    qDebug() << payload;

    QString json = payload;
    QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
    if(doc.isObject())
    {
        qDebug() << true;
    }
    else
    {
        qDebug()<< false;
    }
    QJsonObject object = doc.object();
    QJsonValue temp = object["temp"];
    QJsonValue hum = object ["hum"];
    QJsonValue lht = object ["lht"];
    QJsonValue som = object ["som"];

    GlobalVal::temp = temp.toInt();
    GlobalVal::hum = hum.toInt();
    GlobalVal::lht = lht.toInt();
    GlobalVal::som = som.toInt();
    ui->lcd_temp->display(temp.toInt());
    ui->lcd_humi->display(hum.toInt());
    ui->lcd_lht->display(lht.toInt());
    ui->lcd_lht_2->display(som.toInt());

}

void Stm32Wig::updateTime()
{
    ui->label->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
}

void Stm32Wig::on_pushButton_clicked()
{
    QJsonObject object;
    object["mode"] = 3;

    QJsonDocument doc(object);
    QByteArray json = doc.toJson();
    QMQTT::Message msg;
    msg.setPayload(json);
    msg.setTopic("/app/data/down");

    GlobalVal::mqtt->publish(msg);
}
